<template>
  <el-card shadow="hover" class="mt-20">
    <!-- 
      表单校验
      1.定义三个响应式数据
      2.form加三个属性
      3.给form每一个子元素加prop属性，数据对应规则
     -->
    <!-- 
      收集表单
      1.输入框input v-model
      2.特殊，下拉框select 利用数组下标才可以收集到多个select数据
        v-model="skuFormData.skuAttrValueList[index]
      3.收集图片列表table
        @selection-change="handleSelectionChange"
        const handleSelectionChange = (val) => {
          skuFormData.skuImageList = val;
        };
      -->
    <el-form
      label-width="100px"
      ref="skuFormRef"
      :rules="skuFormRules"
      :model="skuFormData"
    >
      <el-form-item label="SPU 名称">{{ spuStore.spu.spuName }}</el-form-item>
      <el-form-item label="SKU 名称" prop="skuName">
        <el-input placeholder="SKU 名称" v-model="skuFormData.skuName" />
      </el-form-item>
      <el-form-item label="价格(元)" prop="price">
        <el-input-number
          placeholder="价格(元)"
          controls-position="right"
          :min="0"
          class="addSku__input-number"
          v-model="skuFormData.price"
        />
      </el-form-item>
      <el-form-item label="重量(千克)" prop="weight">
        <el-input-number
          placeholder="重量(千克)"
          controls-position="right"
          :min="0"
          class="addSku__input-number"
          v-model="skuFormData.weight"
        />
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          placeholder="规格描述"
          type="textarea"
          :rows="3"
          v-model="skuFormData.skuDesc"
        />
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <!-- row行 col列 gutter列之间的间距 -->
        <el-row :gutter="10" class="addSku__row">
          <el-col
            :xs="24"
            :sm="12"
            :lg="8"
            :xl="4"
            v-for="(attr, index) in attrList"
            :key="attr.id"
          >
            <div class="addSku__col-wrap">
              <span class="addSku__col-title">{{ attr.attrName }}</span>
              <!-- 
                问题：收集只能收集到一个select
                解决：用数组下标，获取对应的元素，没有获取的就是undefined
                  v-model="skuFormData.skuAttrValueList[index]"
                  v-model="skuFormData.skuSaleAttrValueList[index]"
                如果只要收集一个数据，直接写，
                收集多个数据，可以字符串拼接起来 
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName} `"
                  :value="`${spuSaleAttr.id}:${spuSaleAttr.saleAttrName}:${spuSaleAttrValue.id}:${spuSaleAttrValue.saleAttrValueName}`"
               -->
              <el-select
                placeholder="请选择"
                v-model="skuFormData.skuAttrValueList[index]"
              >
                <el-option
                  :label="attrValue.valueName"
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName} `"
                  v-for="attrValue in attr.attrValueList"
                  :key="attrValue.id"
                ></el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row :gutter="10" class="addSku__row">
          <el-col
            v-for="(spuSaleAttr, index) in spuSaleAttrList"
            :key="spuSaleAttr.id"
            :xs="24"
            :sm="12"
            :lg="8"
            :xl="4"
          >
            <div class="addSku__col-wrap">
              <span class="addSku__col-title">{{
                spuSaleAttr.saleAttrName
              }}</span>
              <el-select
                placeholder="请选择"
                v-model="skuFormData.skuSaleAttrValueList[index]"
              >
                <el-option
                  :label="spuSaleAttrValue.saleAttrValueName"
                  :value="`${spuSaleAttr.id}:${spuSaleAttr.saleAttrName}:${spuSaleAttrValue.id}:${spuSaleAttrValue.saleAttrValueName}`"
                  v-for="spuSaleAttrValue in spuSaleAttr.spuSaleAttrValueList"
                  :key="spuSaleAttrValue.id"
                ></el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          :data="spuImageList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img :src="row.imgUrl" :alt="row.imgName" class="addSku__img" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <!-- 
                设置默认 
                默认都是button 点击变tag 
                排他: 只有一个tag
                
              -->
              <el-tag type="success" v-if="row.isDefault === '1'">默认</el-tag>
              <el-button
                type="primary"
                size="small"
                v-else
                @click="setIsDefaultImg(row)"
                >设置默认</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AddSku",
};
</script>

<script lang="ts" setup>
import { getSpuImageListApi, getSpuSaleAttrListApi } from "@/api/product/spu";
import { getAttrListApi } from "@/api/product/attr";
import type {
  SpuImageList,
  SpuSaleAttrList,
} from "@/api/product/model/spuModel";
import type { AttrList } from "@/api/product/model/attrModel";
import { useSpuStore } from "@/stores/spu";
import { useCategoryStore } from "@/stores/category";
import { onMounted, ref, reactive } from "vue";
import {
  SkuFormData,
  SkuImageList,
  SkuImageItem,
} from "@/api/product/model/skuModel";
import { addSkuApi } from "@/api/product/sku";
import { ElMessage } from "element-plus";
// 请求获取数据
const spuStore = useSpuStore();
const categoryStore = useCategoryStore();
const attrList = ref<AttrList>();
const spuImageList = ref<SpuImageList>();
const spuSaleAttrList = ref<SpuSaleAttrList>();
onMounted(async () => {
  const { category1Id, category2Id, category3Id } = categoryStore;
  attrList.value = await getAttrListApi({
    category1Id: category1Id as number,
    category2Id: category2Id as number,
    category3Id: category3Id as number,
  });
});
onMounted(async () => {
  spuSaleAttrList.value = await getSpuSaleAttrListApi(
    spuStore.spu.id as number
  );
});
onMounted(async () => {
  spuImageList.value = await getSpuImageListApi(spuStore.spu.id as number);
});

// 表单校验
const skuFormRef = ref();
const skuFormData = reactive<SkuFormData>({
  skuName: "",
  price: undefined,
  weight: undefined,
  skuDesc: "",
  skuAttrValueList: [
    // {
    //   attrId: 0,
    //   attrName: "string",
    //   id: 0,
    //   skuId: 0,
    //   valueId: 0,
    //   valueName: "string",
    // },
  ],
  skuSaleAttrValueList: [
    // {
    //   id: 0,
    //   saleAttrId: 0,
    //   saleAttrName: "string",
    //   saleAttrValueId: 0,
    //   saleAttrValueName: "string",
    //   skuId: 0,
    //   spuId: 0,
    // },
  ],
  skuDefaultImg: "",
  skuImageList: [
    // {
    //   id: 0,
    //   imgName: "string",
    //   imgUrl: "string",
    //   isDefault: "string",
    //   skuId: 0,
    //   spuImgId: 0,
    // },
  ],
});
// 自定义图片列表校验规则
const skuImageListValidator = (
  rule: any,
  value: SkuImageList,
  callback: any
) => {
  // 1.图片列表中必须要选择一张图片
  if (!value.length) {
    callback(new Error("至少选择一个图片"));
  }
  // 2.选中图片必须要有默认图片
  if (!value.some((img) => img.isDefault === "1")) {
    callback(new Error("选中图片必须要有默认图片"));
  }
  callback();
};
const skuFormRules = reactive({
  skuName: [{ required: true, message: "请输入SKU名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入SKU价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入SKU重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入SKU描述", trigger: "blur" }],
  skuAttrValueList: [
    { required: true, message: "请选择SKU平台属性", trigger: "change" },
  ],
  skuSaleAttrValueList: [
    { required: true, message: "请选择SKU销售属性", trigger: "change" },
  ],
  skuImageList: [{ required: true, validator: skuImageListValidator }],
});
// 收集table的图片列表
const handleSelectionChange = (val: SkuImageList) => {
  skuFormData.skuImageList = val;
};
// 设置默认图片
const setIsDefaultImg = (row: SkuImageItem) => {
  // 排他：遍历所有的都改为'0',自己的改为'1'
  spuImageList.value?.forEach((img) => (img.isDefault = "0"));
  row.isDefault = "1";
  // 修改默认图片
  skuFormData.skuDefaultImg = row.imgUrl;
  // 选中图片中有默认图片才清空校验提示
  if (skuFormData.skuImageList.some((img) => img === row)) {
    skuFormRef.value.clearValidate(["skuImageList"]);
  }
};

// 提交表单
const submit = async () => {
  // 校验整个表单
  await skuFormRef.value.validate();
  // 发送请求，添加sku
  const data = {
    ...skuFormData,
    category3Id: categoryStore.category3Id as number,
    spuId: spuStore.spu.id as number,
    // filter(Boolean) 等同于 filter(item => {Boolean(item)}) 把每一个元素转布尔值，过滤出true的
    skuAttrValueList: skuFormData.skuAttrValueList
      .filter(Boolean)
      .map((attr) => {
        const [attrId, attrName, valueId, valueName] = (attr as string).split(
          ":"
        );
        return {
          attrId: +attrId,
          attrName,
          valueId: +valueId,
          valueName,
        };
      }),
    skuSaleAttrValueList: skuFormData.skuSaleAttrValueList
      .filter(Boolean)
      .map((attr) => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = (
          attr as string
        ).split(":");
        return {
          saleAttrId: +saleAttrId,
          saleAttrName,
          saleAttrValueId: +saleAttrValueId,
          saleAttrValueName,
        };
      }),
  };
  await addSkuApi(data);
  ElMessage.success("添加SKU成功~");
  cancel();
};
const emit = defineEmits(["setIsShow"]);
const cancel = () => {
  emit("setIsShow", 1);
};
</script>

<style scoped>
.addSku__input-number {
  width: 100%;
}
:deep(.el-input__inner) {
  text-align: left;
}
.addSku__img {
  width: 100px;
}
.addSku__row {
  width: 100%;
}
.addSku__col-wrap {
  display: flex;
  margin-bottom: 10px;
}
.addSku__col-title {
  flex-grow: 1;
  text-align: right;
  margin-right: 10px;
}
</style>
